package com.huayi.website.repository;


import com.huayi.website.entity.ManageUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 描述：
 * 管理员Repository
 *
 * @author qlp
 * @date 2018-12-26 5:05 PM
 */
@Repository
public class ManageUserRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据用户名查询用户
     *
     * @param userName
     * @return
     */
    public ManageUserEntity getUserByUserName(String userName) {
        String sql = "SELECT * FROM " + Tables.ManageUser + " WHERE user_name=? or mobile= ? LIMIT 1";
        List<ManageUserEntity> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ManageUserEntity.class), userName, userName);
        if (users == null || users.size() == 0) return null;
        else return users.get(0);
    }

    /**
     * 根据货id查詢用戶姓名
     *
     * @return
     */
    public String getNameById(Integer id) {
        String userName;
        try {
            userName = jdbcTemplate.queryForObject("SELECT true_name FROM " + Tables.ManageUser + " WHERE id = ? ", String.class, id);
        } catch (EmptyResultDataAccessException e) {
            userName = "";
        }
        return userName;
    }

    /**
     * 根据用户Id查询管理员信息根据用户Id查询管理员信息
    /*
     * 根据用户Id查询管理员信息
     * @param userId
     * @return
     */
    public ManageUserEntity getManageUserById(Integer userId){
        try {
            return jdbcTemplate.queryForObject("SELECT * FROM " + Tables.ManageUser + " WHERE id=?",new BeanPropertyRowMapper<>(ManageUserEntity.class),userId);
        }catch (Exception e){
            return null;
        }

    }

    /**
     * 修改用户登录密码
     *
     * @param newPwd
     * @return
     */
    public void updManageUserPwd(int userId, String newPwd, String pwd_rand) {
        jdbcTemplate.update("UPDATE "+Tables.ManageUser +" SET user_pwd = ?,user_salf=? WHERE id = ? ", newPwd, pwd_rand, userId);
    }
}
